package com.heima.wemedia.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dto.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class WmNewsAutoScanServiceImpl extends ServiceImpl<WmNewsMapper,WmNews> implements WmNewsAutoScanService{
    @Resource
    private  WmNewsMapper wmNewsMapper;
    @Resource
    private GreenTextScan greenTextScan;

    @Override
    @Async
    public void autoScanWmNews(Integer id) {
        try {
            //查询自媒体
            WmNews wmNews = wmNewsMapper.selectById(id);
            // 提前检查 wmNews 是否为 null
            if(wmNews == null){
                throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在");
            }
            log.info("{图片}",wmNews.getImages());
            //从内容中提取纯文本和图片
            Map<String,Object> textAndImage=handleTextAndImage(wmNews);
            //自管理敏感词
            boolean isSensitive=handleSensitiveScan((String)textAndImage.get("text"),wmNews);
            if(!isSensitive){
                if(wmNews.getStatus() == WmNews.Status.SUBMIT.getCode()){
                    updateWmNews(wmNews,(short)2,"含有敏感词");
                }
                return;
            }
            //审核文本内容 阿里云接口
            boolean isTextScan=handleTextScan((String)textAndImage.get("text"),wmNews);
            if(!isTextScan){
                if(wmNews.getStatus() == WmNews.Status.SUBMIT.getCode()){
                    updateWmNews(wmNews,(short)3,"文本审核未通过或异常，转人工审核");
                }
                return;
            }
            //审核图片 阿里云接口
            boolean isImagesScan=handleImageScan((List<String>) textAndImage.get("images"),wmNews);
            if(!isImagesScan){
                // 图片审核不通过，更新文章状态
                updateWmNews(wmNews, (short) 2, "图片审核不通过");
                return;
            }
            //审核成功 保存app端的相关文章数据
            ResponseResult responseResult = saveAppArticle(wmNews);
            if (responseResult.getCode()!=200){
                throw new RuntimeException("WmNewsAutoScanServiceImpl-保存app端相关文章数据失败");
            }
            wmNews.setArticleId((Long) responseResult.getData());
            updateWmNews(wmNews,(short) 9,"审核成功");
        } catch (Exception e) {
            log.error("自媒体文章自动审核异常 id={}", id, e);
            try {
                WmNews wmNews = wmNewsMapper.selectById(id);
                if(wmNews != null){
                    updateWmNews(wmNews,(short)3,"自动审核异常，转人工审核");
                }
            } catch (Exception ignore) {}
        }

    }

    @Resource
    private WmSensitiveMapper wmSensitiveMapper;
    private boolean handleSensitiveScan(String textAndImage, WmNews wmNews) {
        boolean flag=true;
        List<WmSensitive> wmSensitives = wmSensitiveMapper
                .selectList(Wrappers.<WmSensitive>lambdaQuery()
                        .select(WmSensitive::getSensitives));
        List<String> stringList = wmSensitives.stream()
                .map(WmSensitive::getSensitives).collect(Collectors.toList());
        SensitiveWordUtil.initMap(stringList);
        Map<String, Integer> stringIntegerMap = SensitiveWordUtil.matchWords(textAndImage);
        if(!stringIntegerMap.isEmpty()){
            updateWmNews(wmNews,(short) 2,"含有敏感词"+stringIntegerMap);
            flag=false;

        }
        return flag;

    }

    @Resource
    WmChannelMapper wmChannelMapper;
    @Resource
    WmUserMapper wmUserMapper;
    private ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto dto=new ArticleDto();
        BeanUtils.copyProperties(wmNews,dto);
        dto.setLayout(wmNews.getType());
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if(wmNews.getChannelId()!=null){
            dto.setChannelName(wmChannel.getName());
        }
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmUser != null){
            dto.setAuthorName(wmUser.getName());
        }

        if(wmNews.getArticleId()!=null){
            dto.setId(wmNews.getArticleId());
        }
        dto.setCreatedTime(new Date());

        ResponseResult responseResult = iArticleClient.saveArticle(dto);


        return responseResult;
    }

    @Autowired
    IArticleClient iArticleClient;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private GreenImageScan greenImageScan;
    @Resource
    private Tess4jClient tess4jClient;
    private boolean handleImageScan(List<String> images, WmNews wmNews) {
            boolean flag=true;
            log.info("封面图片审核开始,{}", images);
            if(images==null||images.isEmpty()){
                log.info("图片审核结束,{}",images);
                return flag;}
//        images= images.stream().distinct().collect(Collectors.toList());
//        List<byte[]> imagesList=new ArrayList<>();
        List<String> distinctImages = images.stream().distinct().collect(Collectors.toList());
        List<String> imageStrings = new ArrayList<>(); // 存储转换后的字符串列表
        try {
            for(String imagePath:distinctImages){
                byte[] imageBytes=fileStorageService.downLoadFile(imagePath);
                ByteArrayInputStream in = new ByteArrayInputStream(imageBytes);
                BufferedImage image = ImageIO.read(in);
                log.info("图片识别的内容：{}", image);
                String doOCR = tess4jClient.doOCR(image);
                boolean sensitiveScan = handleSensitiveScan(doOCR, wmNews);
                log.info("图片内容：{}", doOCR);
                if (!sensitiveScan){
                    log.info("cg：{}", sensitiveScan);
                    return sensitiveScan;
                }
//                if (imageBytes != null) { // 避免空字节数组
//                    // 用 Base64 编码将 byte[] 转为 String（二进制安全转换）
//                    String base64Str = Base64.getEncoder().encodeToString(imageBytes);
//                    imageStrings.add(base64Str);
//                } else {
//                    // 处理下载失败的情况（如日志记录）
//                    log.info("图片下载失败：{}" , imagePath);
//                    flag = false; // 可选：下载失败视为扫描不通过
//                }
            }
        } catch (Exception e) {
           e.printStackTrace();
        }

        try {
            // 若没有可扫描的图片（全下载失败），直接返回
            if (imageStrings.isEmpty()) {
                return flag;
            }
            Map map=greenImageScan.imageScan(imageStrings);
            if(map!=null){
                if(map.get("suggestion").equals("block")){
                    flag=false;
                    updateWmNews(wmNews,(short) 2,"当前文章存在违规内容");
                }
                if(map.get("suggestion").equals("review")){
                    flag=false;
                    updateWmNews(wmNews,(short) 3,"当前文章存在不确定内容");
                }
            }
        } catch (Exception e) {
            flag=false;
          e.printStackTrace();
        }
        return flag;
    }
/**
     * 文本审核
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content,WmNews wmNews){
        boolean flag=true;
        if((content+"-"+wmNews.getTitle()).length()==0){
            return flag;
        }
        try {
            Map map=greenTextScan.greeTextScan(content+"-"+wmNews.getTitle());
            if(map!=null){
                //审核失败
                log.info("suggestion,{}", map.get("suggestion"));
                if(map.get("suggestion").equals("block")){
                    flag=false;
                    updateWmNews(wmNews,(short)2, "当前文章存在违规内容");

                }
                if(map.get("suggestion").equals("review")){
                    flag=false;
                    updateWmNews(wmNews, (short)3, "当前文章存在不确定的内容");
                }
            }
        } catch (Exception e) {
            flag=false;
            e.printStackTrace();
        }
        return flag;
    }
    /**
     * 敏感词审核
     * @param textAndImage
     * @param wmNews
     * @return
     */

    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus( status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

/**
     * 敏感词审核
     * @param textAndImage
     * @param wmNews
     * @return
     */
    private Map<String,Object> handleTextAndImage(WmNews wmNews){
        //存储纯文本文件
        StringBuilder stringBuilder=new StringBuilder();
        List<String> images=new ArrayList<>();
        //1 从自媒体文章中提取纯文本内容和图片
        if(StringUtils.isNotBlank(wmNews.getContent())){
            List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
            for(Map map:maps) {
                if (map.get("type").equals("text")) {
                    log.info("text,{}", map.get("value"));
                    stringBuilder.append(map.get("value"));
                }
                if (map.get("type").equals("image")) {
                    log.info("image,{}", map.get("value"));
                    images.add((String) map.get("value"));
                }
            }
        }
        //提取封面
        if(StringUtils.isNotBlank(wmNews.getImages())){
            String[] split=wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }
        //封装结果返回
        Map<String,Object> resultmap=new HashMap<>();
        resultmap.put("text",stringBuilder.toString());
        resultmap.put("images",images);
        return resultmap;
    }

}
